package com.whub507.msgmanager.sso.client.sso;

import com.whub507.msgmanager.sso.client.sso.pki.PKIUtils;
import org.springframework.security.jwt.crypto.sign.InvalidSignatureException;
import org.springframework.security.jwt.crypto.sign.SignerVerifier;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.Signature;
import java.security.cert.X509Certificate;

/**
 * JWT签名对象，只提供验证方法，不提供签名方法，用于SSO Client&Server验证令牌合法性
 * 
 * @author wcl
 *
 */
public class SSOVerifySigner implements SignerVerifier {

//	private final Logger logger = LoggerFactory.getLogger(getClass());

	private Signature sigPublic;

	public SSOVerifySigner(byte[] bytes) throws Exception {
		try (InputStream istreamCert = new ByteArrayInputStream(bytes)) {
			X509Certificate cert = PKIUtils.loadCertificate(istreamCert);
			sigPublic = PKIUtils.getSignature(cert);
		}
	}

	@Override
	public byte[] sign(byte[] bytes) {
		throw new RuntimeException("This method does not work!");
	}

	@Override
	public String algorithm() {
		// String alg = sigPublic.getAlgorithm();
		String alg = "SHA256withRSA";
		return alg;
	}

	@Override
	public void verify(byte[] content, byte[] signature) {
		try {
			sigPublic.update(content);
			boolean bool = sigPublic.verify(signature);
			if (!bool) {
				throw new InvalidSignatureException("Calculated signature did not match actual value");
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
